package com.snopy.concurrency.createthread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author snopy
 * @version 1.0.0
 * @classname ThreadDemo
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/22 14:35
 */
@Slf4j
public class ThreadDemo {

    //sleep(time) 和 yield() 都是哪个线程调用，就让出哪个线程，不同点在于，sleep需要加一个时间，调用后，线程就会进入TIME_WAITING状态
    //yield()也会让出当前cpu的使用，但是状态是变为RUNNABLE,如果没有其他的线程使用cpu，还是会继续变成RUNNING状态，继续执行
    public static void main(String[] args) throws InterruptedException {

        //1.1.直接定义线程
        Thread thread = new Thread(new Thread(){
            //1.2.重写run方法
            @Override
            public void run() {
                log.info("this is a thread!开始睡觉");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("{} sleep over",this.getName());
                    for (int i = 0; i < Integer.MAX_VALUE; i++) {
                        if (i%200000000==0){
                            log.info("---{}---",i);
                        }
                    }
                    log.info("上山打老虎------");

            }
        },"customTd");
        Thread t1 = new Thread(()->{
            log.info("print num--------");
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                if (i%200000000==0){
                    log.info("current num:{}",i);
                }
                if (i%1000000000==0){
                    log.info("current num is :{},让出资源",i);
                    Thread.yield();
                }

            }
        });
        //1.3.启动
        thread.start();
        t1.start();

        Thread thread1 = new Task("snoopy");
        thread1.start();
        log.info("state:{}",thread.getState());
    }



}
class Task extends Thread{
    private String name;


    public Task(String name) {
        this.name = name;
    }



    @Override
    public void run() {
        System.out.println("执行要执行的任务"+name+this.getName());
    }
}